const crypto = require('crypto');


const key = require('../servers/connector/domain/centerManager').key;
const iv = '11HABSGEEHJGHE22';
const TOKEN_USEFUL_TIME = 30000;

module.exports.createToken = function (uid, serverID) {

    let data = Date.now() + '|' + uid + '|' + serverID;
    let cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
    let encrypted = cipher.update(data, 'utf8', 'hex');
    encrypted += cipher.final('hex');

    return encrypted;
}


module.exports.createMsg = function (data) {

    if (typeof data == `object`) {
        data = JSON.stringify(data);
    }
    let cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
    let encrypted = cipher.update(data, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return encrypted;

}

module.exports.getMsg = function (data) {


    let decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    let decrypted = decipher.update(data, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;

}


module.exports.parseToken = function (token) {

    let decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    let decrypted = decipher.update(token, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    let ts = decrypted.split('|');
    if (ts.length !== 3) {

        return null;
    }
    return { uid: ts[1], serverID: ts[2], timekey: Number(ts[0]) };

}


module.exports.checkToken = function (authInfo) {
    if (!authInfo || !authInfo.serverID || !authInfo.timekey || !authInfo.uid) {
        return false;
    }
    let nowTime = Date.now();
    return ((nowTime - authInfo.timekey) < TOKEN_USEFUL_TIME);
};